package com.czk.zookeeper.curator.watcher;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/7 22:05
 */
public class CuratorWatcherTest {
    String IP = "192.168.25.133:2181,192.168.25.133:2182,192.168.25.133:2183";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(50000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        // 监视某个节点的数据变化
        final NodeCache nodeCache = new NodeCache(client, "/watcher");
        // 启动监视器对象
        nodeCache.start();

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                // 路径
                System.out.println(nodeCache.getCurrentData().getPath());
                // 数据
                System.out.println(new String(nodeCache.getCurrentData().getData()));
            }
        });
        Thread.sleep(100000);
        System.out.println("启动成功");
        nodeCache.close();
    }

    /**
     * 监控子节点
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        // 监视子节点的变化
        // arg1 连接对象
        // agr2 监视节点路径
        // arg3 事件中是否可以获取节点的数据
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/watcher", true);
        pathChildrenCache.start();
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                System.out.println(pathChildrenCacheEvent.getType());
                // 路径
                System.out.println(pathChildrenCacheEvent.getData().getPath());
                // 节点数据
                System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
            }
        });
        System.in.read();
        System.out.println("结束");
    }

    @Test
    public void test3() throws Exception {

    }

}
